package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"stream-mgmt/cache"
	"stream-mgmt/models"
	"stream-mgmt/pkg"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不能为空",
		})
		return
	}
	redis_login_key := "redis_login_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_login_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
		return
	}
	var user models.User
	err := models.DB.Where("username = ?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
		return
	}
	if user.Password != pkg.MD5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_login_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_login_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误三次，封禁2小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": user,
	})
	return
}
func Node(c *gin.Context) {
	rid := c.Query("rid")
	/*
		SELECT
		  role_nodes.id as ID,
		  nodes.node_name as NodeName
		FROM
		  nodes
		  LEFT JOIN role_nodes ON role_nodes.nid = nodes.id
		WHERE
		  role_nodes.nid = 1
	*/
	var node models.NodeRole
	models.DB.Table("nodes").
		Select(
			"role_nodes.id as ID",
			"nodes.node_name as NodeName",
		).
		Joins("LEFT JOIN role_nodes ON role_nodes.nid = nodes.id").
		Where("role_nodes.nid = ?", rid).
		Debug().
		Find(&node)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "success",
		"data": node,
	})
	return
}
func Role(c *gin.Context) {
	uid := c.Query("uid")
	/*
		SELECT
		  user_roles.id as ID,
		  roles.role_name as RoleName
		FROM
		  roles
		  LEFT JOIN user_roles ON user_roles.rid = roles.id
		WHERE
		  user_roles.rid = 1
	*/

	var role models.RoleUser
	models.DB.Table("roles").
		Select(
			"user_roles.id as ID",
			"roles.role_name as RoleName",
		).
		Joins("LEFT JOIN user_roles ON user_roles.rid = roles.id").
		Where("user_roles.rid = ?", uid).
		Debug().
		Find(&role)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "success",
		"data": role,
	})
	return
}
func Add(c *gin.Context) {
	ShopName := c.PostForm("ShopName")
	Stat := c.PostForm("Stat")
	if ShopName == "" || Stat == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不能为空",
		})
		return
	}
	var shop = models.Shop{

		ShopName: ShopName,
		Stat:     Stat,
	}
	err := models.DB.Create(&shop).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func OrderAdd(c *gin.Context) {
	OrderName := c.PostForm("OrderName")
	Price, _ := strconv.Atoi(c.PostForm("Price"))
	Pid, _ := strconv.Atoi(c.PostForm("Pid"))
	if OrderName == "" || Price == 0 || Pid == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不能为空",
		})
		return
	}
	var order = models.Order{

		OrderName: OrderName,
		Price:     Price,
		Pid:       Pid,
	}
	err := models.DB.Create(&order).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var list []models.Put
	redis_list_key := "redis_list_" + strconv.Itoa(page)
	result, _ := cache.Rdb.Get(cache.Ctx, redis_list_key).Result()
	if result == "" {
		models.DB.Table("orders").
			Select(
				"orders.id as ID",
				"orders.order_name as OrderName",
				"orders.price as Price",
				"shops.shop_name as ShopName",
				"shops.stat as Stat",
			).
			Joins("LEFT JOIN shops ON orders.pid = shops.id").
			Debug().
			Offset(offset).
			Limit(size).
			Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_list_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &list)
	}
	var total int64
	models.DB.Model(&models.Order{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "success",
		"data":  list,
		"total": total,
	})
	return
}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var detail models.Order
	redis_detail_key := "redis_detail_" + id
	result, _ := cache.Rdb.Get(cache.Ctx, redis_detail_key).Result()
	if result == "" {
		models.DB.Where("id = ?", id).First(&detail)
		jsonData, _ := json.Marshal(detail)
		cache.Rdb.Set(cache.Ctx, redis_detail_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &detail)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询详情成功",
		"data": detail,
	})
	return
}
